package net.xdclass.xdclassmq.jms.consumer;

import net.xdclass.xdclassmq.config.JmsConfig;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class PayOrderlyConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    private JmsConfig jmsConfig;

    public PayOrderlyConsumer(){
    }

    @Bean
    public void payOrderlyConsumerListener() throws MQClientException {
        consumer = new DefaultMQPushConsumer(jmsConfig.getPayOrderlyConsumerGroup());
        consumer.setNamesrvAddr(jmsConfig.getNameServerAddr());
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);

        consumer.setMessageModel(MessageModel.CLUSTERING);
        consumer.subscribe(jmsConfig.getOrderlyTopic(),"*");
        consumer.setConsumeThreadMin(1);
        consumer.setConsumeThreadMax(1);

        consumer.registerMessageListener((MessageListenerOrderly) (msgs, context) -> {
            MessageExt msg = msgs.get(0);
            try{
                System.out.printf("%s Receive New Messages: %s %n",
                        Thread.currentThread().getName(),
                        new String(msg.getBody(),"UTF-8"));
                return ConsumeOrderlyStatus.SUCCESS;
            }catch (Exception e) {
                e.printStackTrace();
                return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
            }

        });
        consumer.start();
        System.out.println("consumer start ...");
    }
}
